package com.alvis.media.controller.admin;

import com.alvis.media.base.BaseApiController;
import com.alvis.media.base.RestResponse;
import com.alvis.media.viewmodel.admin.netflix.*;
import lombok.AllArgsConstructor;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Netflix数据分析Controller
 */
@RestController("NetflixAnalysisController")
@RequestMapping(value = "/api/admin/netflix")
@AllArgsConstructor
public class NetflixAnalysisController extends BaseApiController {

    private static String CSV_FILE_PATH = "d:\\DaSi\\ChuanMeiShuJu\\ss\\mediaAnalysisSystem\\netflix_titles.csv.csv";

    /**
     * 上传CSV数据集
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public RestResponse<Map<String, Object>> uploadDataset(@RequestParam("file") MultipartFile file) {
        try {
            // 校验文件
            if (file.isEmpty()) {
                return RestResponse.fail(400, "文件为空");
            }
            
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !originalFilename.endsWith(".csv")) {
                return RestResponse.fail(400, "请上传CSV格式的文件");
            }
            
            // 保存文件到项目目录
            String projectPath = System.getProperty("user.dir");
            String uploadDir = projectPath + File.separator + "uploads";
            
            // 创建目录
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            
            // 保存为固定名称，覆盖旧文件
            String fileName = "uploaded_dataset.csv";
            Path filePath = Paths.get(uploadDir, fileName);
            
            // 保存文件
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
            
            // 更新CSV文件路径
            CSV_FILE_PATH = filePath.toString();
            
            // 读取CSV文件头，分析可用字段
            Reader reader = new FileReader(CSV_FILE_PATH);
            CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader());
            
            Set<String> headers = csvParser.getHeaderMap().keySet();
            csvParser.close();
            
            // 返回上传结果和字段信息
            Map<String, Object> result = new HashMap<>();
            result.put("message", "数据集上传成功！");
            result.put("filePath", CSV_FILE_PATH);
            result.put("fileName", originalFilename);
            result.put("headers", headers);
            
            return RestResponse.ok(result);
        } catch (IOException e) {
            return RestResponse.fail(500, "文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前数据集信息
     */
    @RequestMapping(value = "/datasetInfo", method = RequestMethod.GET)
    public RestResponse<Map<String, Object>> getDatasetInfo() {
        try {
            File csvFile = new File(CSV_FILE_PATH);
            Map<String, Object> info = new HashMap<>();
            
            if (csvFile.exists()) {
                info.put("fileName", csvFile.getName());
                info.put("filePath", CSV_FILE_PATH);
                info.put("fileSize", csvFile.length());
                info.put("exists", true);
            } else {
                info.put("exists", false);
                info.put("message", "数据集文件不存在");
            }
            
            return RestResponse.ok(info);
        } catch (Exception e) {
            return RestResponse.fail(500, "获取数据集信息失败：" + e.getMessage());
        }
    }

    /**
     * 通用字段分析 - 根据字段名称进行统计
     */
    @RequestMapping(value = "/analysis/fieldDistribution", method = RequestMethod.POST)
    public RestResponse<Map<String, Object>> getFieldDistribution(@RequestBody Map<String, String> params) {
        try {
            String fieldName = params.get("fieldName");
            String chartType = params.getOrDefault("chartType", "bar"); // bar, pie, line
            Integer topN = Integer.parseInt(params.getOrDefault("topN", "10"));
            
            if (fieldName == null || fieldName.isEmpty()) {
                return RestResponse.fail(400, "字段名不能为空");
            }
            
            Map<String, Integer> fieldCount = new HashMap<>();
            
            Reader reader = new FileReader(CSV_FILE_PATH);
            CSVParser csvParser = new CSVParser(reader, 
                CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());
            
            // 检查字段是否存在
            if (!csvParser.getHeaderMap().containsKey(fieldName)) {
                csvParser.close();
                return RestResponse.fail(400, "字段 '" + fieldName + "' 不存在，可用字段：" + csvParser.getHeaderMap().keySet());
            }
            
            for (CSVRecord record : csvParser) {
                String value = record.get(fieldName);
                if (value != null && !value.isEmpty()) {
                    // 处理逗号分隔的多值字段
                    if (value.contains(",")) {
                        String[] values = value.split(",");
                        for (String v : values) {
                            String trimmed = v.trim();
                            if (!trimmed.isEmpty()) {
                                fieldCount.put(trimmed, fieldCount.getOrDefault(trimmed, 0) + 1);
                            }
                        }
                    } else {
                        fieldCount.put(value, fieldCount.getOrDefault(value, 0) + 1);
                    }
                }
            }
            csvParser.close();
            
            // 排序并获取Top N
            List<Map.Entry<String, Integer>> sortedEntries = fieldCount.entrySet().stream()
                    .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                    .limit(topN)
                    .collect(Collectors.toList());
            
            List<String> labels = sortedEntries.stream()
                    .map(Map.Entry::getKey)
                    .collect(Collectors.toList());
            List<Integer> counts = sortedEntries.stream()
                    .map(Map.Entry::getValue)
                    .collect(Collectors.toList());
            
            Map<String, Object> result = new HashMap<>();
            result.put("labels", labels);
            result.put("counts", counts);
            result.put("title", fieldName + " 分布统计 (Top " + topN + ")");
            result.put("chartType", chartType);
            result.put("totalRecords", fieldCount.values().stream().mapToInt(Integer::intValue).sum());
            
            return RestResponse.ok(result);
        } catch (IOException e) {
            return RestResponse.fail(500, "读取CSV文件失败：" + e.getMessage());
        } catch (Exception e) {
            return RestResponse.fail(500, "分析失败：" + e.getMessage());
        }
    }

    /**
     * 模型1: 按年份统计电影数量
     */
    @RequestMapping(value = "/analysis/yearDistribution", method = RequestMethod.POST)
    public RestResponse<NetflixYearDistributionVM> getYearDistribution() {
        try {
            Map<String, Integer> yearCount = new HashMap<>();
            
            Reader reader = new FileReader(CSV_FILE_PATH);
            CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());
            
            for (CSVRecord record : csvParser) {
                String year = record.get("release_year");
                if (year != null && !year.isEmpty()) {
                    yearCount.put(year, yearCount.getOrDefault(year, 0) + 1);
                }
            }
            csvParser.close();
            
            // 排序并获取数据
            List<String> years = yearCount.keySet().stream()
                    .sorted()
                    .collect(Collectors.toList());
            List<Integer> counts = years.stream()
                    .map(yearCount::get)
                    .collect(Collectors.toList());
            
            NetflixYearDistributionVM vm = new NetflixYearDistributionVM();
            vm.setYears(years);
            vm.setCounts(counts);
            vm.setTitle("电影发行年份分布");
            
            return RestResponse.ok(vm);
        } catch (IOException e) {
            return RestResponse.fail(500, "读取CSV文件失败: " + e.getMessage());
        }
    }

    /**
     * 模型2: 按类型统计(电影 vs 电视剧)
     */
    @RequestMapping(value = "/analysis/typeDistribution", method = RequestMethod.POST)
    public RestResponse<NetflixTypeDistributionVM> getTypeDistribution() {
        try {
            Map<String, Integer> typeCount = new HashMap<>();
            
            Reader reader = new FileReader(CSV_FILE_PATH);
            CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());
            
            for (CSVRecord record : csvParser) {
                String type = record.get("type");
                if (type != null && !type.isEmpty()) {
                    typeCount.put(type, typeCount.getOrDefault(type, 0) + 1);
                }
            }
            csvParser.close();
            
            List<String> types = new ArrayList<>(typeCount.keySet());
            List<Integer> counts = types.stream()
                    .map(typeCount::get)
                    .collect(Collectors.toList());
            
            NetflixTypeDistributionVM vm = new NetflixTypeDistributionVM();
            vm.setTypes(types);
            vm.setCounts(counts);
            vm.setTitle("内容类型分布");
            
            return RestResponse.ok(vm);
        } catch (IOException e) {
            return RestResponse.fail(500, "读取CSV文件失败: " + e.getMessage());
        }
    }

    /**
     * 模型3: 按国家统计(Top 10)
     */
    @RequestMapping(value = "/analysis/countryDistribution", method = RequestMethod.POST)
    public RestResponse<NetflixCountryDistributionVM> getCountryDistribution() {
        try {
            Map<String, Integer> countryCount = new HashMap<>();
            
            Reader reader = new FileReader(CSV_FILE_PATH);
            CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());
            
            for (CSVRecord record : csvParser) {
                String country = record.get("country");
                if (country != null && !country.isEmpty()) {
                    // 处理多个国家的情况(逗号分隔)
                    String[] countries = country.split(",");
                    for (String c : countries) {
                        String trimmedCountry = c.trim();
                        if (!trimmedCountry.isEmpty()) {
                            countryCount.put(trimmedCountry, countryCount.getOrDefault(trimmedCountry, 0) + 1);
                        }
                    }
                }
            }
            csvParser.close();
            
            // 获取Top 10国家
            List<Map.Entry<String, Integer>> sortedEntries = countryCount.entrySet().stream()
                    .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                    .limit(10)
                    .collect(Collectors.toList());
            
            List<String> countries = sortedEntries.stream()
                    .map(Map.Entry::getKey)
                    .collect(Collectors.toList());
            List<Integer> counts = sortedEntries.stream()
                    .map(Map.Entry::getValue)
                    .collect(Collectors.toList());
            
            NetflixCountryDistributionVM vm = new NetflixCountryDistributionVM();
            vm.setCountries(countries);
            vm.setCounts(counts);
            vm.setTitle("内容来源国家分布 (Top 10)");
            
            return RestResponse.ok(vm);
        } catch (IOException e) {
            return RestResponse.fail(500, "读取CSV文件失败: " + e.getMessage());
        }
    }

    /**
     * 模型4: 按评级统计
     */
    @RequestMapping(value = "/analysis/ratingDistribution", method = RequestMethod.POST)
    public RestResponse<NetflixRatingDistributionVM> getRatingDistribution() {
        try {
            Map<String, Integer> ratingCount = new HashMap<>();
            
            Reader reader = new FileReader(CSV_FILE_PATH);
            CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());
            
            for (CSVRecord record : csvParser) {
                String rating = record.get("rating");
                if (rating != null && !rating.isEmpty()) {
                    ratingCount.put(rating, ratingCount.getOrDefault(rating, 0) + 1);
                }
            }
            csvParser.close();
            
            // 按数量排序
            List<Map.Entry<String, Integer>> sortedEntries = ratingCount.entrySet().stream()
                    .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                    .collect(Collectors.toList());
            
            List<String> ratings = sortedEntries.stream()
                    .map(Map.Entry::getKey)
                    .collect(Collectors.toList());
            List<Integer> counts = sortedEntries.stream()
                    .map(Map.Entry::getValue)
                    .collect(Collectors.toList());
            
            NetflixRatingDistributionVM vm = new NetflixRatingDistributionVM();
            vm.setRatings(ratings);
            vm.setCounts(counts);
            vm.setTitle("内容评级分布");
            
            return RestResponse.ok(vm);
        } catch (IOException e) {
            return RestResponse.fail(500, "读取CSV文件失败: " + e.getMessage());
        }
    }

    /**
     * 模型5: 按流派统计(Top 10)
     */
    @RequestMapping(value = "/analysis/genreDistribution", method = RequestMethod.POST)
    public RestResponse<NetflixGenreDistributionVM> getGenreDistribution() {
        try {
            Map<String, Integer> genreCount = new HashMap<>();
            
            Reader reader = new FileReader(CSV_FILE_PATH);
            CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());
            
            for (CSVRecord record : csvParser) {
                String genres = record.get("listed_in");
                if (genres != null && !genres.isEmpty()) {
                    // 处理多个流派的情况(逗号分隔)
                    String[] genreArray = genres.split(",");
                    for (String genre : genreArray) {
                        String trimmedGenre = genre.trim();
                        if (!trimmedGenre.isEmpty()) {
                            genreCount.put(trimmedGenre, genreCount.getOrDefault(trimmedGenre, 0) + 1);
                        }
                    }
                }
            }
            csvParser.close();
            
            // 获取Top 10流派
            List<Map.Entry<String, Integer>> sortedEntries = genreCount.entrySet().stream()
                    .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                    .limit(10)
                    .collect(Collectors.toList());
            
            List<String> genres = sortedEntries.stream()
                    .map(Map.Entry::getKey)
                    .collect(Collectors.toList());
            List<Integer> counts = sortedEntries.stream()
                    .map(Map.Entry::getValue)
                    .collect(Collectors.toList());
            
            NetflixGenreDistributionVM vm = new NetflixGenreDistributionVM();
            vm.setGenres(genres);
            vm.setCounts(counts);
            vm.setTitle("内容流派分布 (Top 10)");
            
            return RestResponse.ok(vm);
        } catch (IOException e) {
            return RestResponse.fail(500, "读取CSV文件失败: " + e.getMessage());
        }
    }
}
